package com.imooc.bilibili.service;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.dao.UserDao;
import com.imooc.bilibili.domain.PageResult;
import com.imooc.bilibili.domain.User;
import com.imooc.bilibili.domain.UserInfo;
import com.imooc.bilibili.domain.constant.UserConstant;
import com.imooc.bilibili.domain.exception.ConditionException;
import com.imooc.bilibili.service.util.MD5Util;
import com.imooc.bilibili.service.util.RSAUtil;
import com.imooc.bilibili.service.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public void addUser(User user) {
        String phone = user.getPhone();
        if (StringUtils.isEmpty(phone)) {
            throw new ConditionException("手机号码不能为空");
        }
        //判断手机号是否存在
        if (null != getUserByPhone(phone)) {
            throw new ConditionException("该用户已存在, 不能重复添加");
        }
        //注册
        Date now = new Date();
        String salt = String.valueOf(now.getTime());
        //解密
        String password = user.getPassword();
        String oldPassword;

        try {
            oldPassword = RSAUtil.decrypt(password);
        } catch (Exception e) {
            throw new ConditionException("密码解密失败");
        }
        //加密
        String newPassword = MD5Util.sign(oldPassword, salt, "utf-8");
        //插入
        user.setCreateTime(now);
        user.setPassword(newPassword);
        user.setSalt(salt);
        userDao.addUser(user);
        //写入user info
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setCreateTime(now);
        userInfo.setBirth(UserConstant.DEFAULT_BIRTH);
        userInfo.setGender(UserConstant.GENDER_MALE);
        userInfo.setNick(UserConstant.DEFAULT_NICK);
        userDao.addUserInfo(userInfo);
    }

    public User getUserByPhone(String phone) {

        return userDao.getUserByPhone(phone);
    }

    public String login(User user) throws Exception {

        //判断手机号不能空
        String phone = user.getPhone();
        if (StringUtils.isEmpty(phone)) {
            throw new ConditionException("手机号码不能为空");
        }
        //判断当前用户不存在
        User dbUser = getUserByPhone(phone);
        if (null == dbUser) {
            throw new ConditionException("当前用户不存在");
        }
        //解密
        String password = user.getPassword();
        String oldPassword;
        try {
            oldPassword = RSAUtil.decrypt(password);
        } catch (Exception e) {
            throw new ConditionException("密码解密失败");
        }
        //加密 判断密码
        String salt = dbUser.getSalt();
        if (!dbUser.getPassword().equals(MD5Util.sign(oldPassword, salt, "utf-8"))) {
            throw new ConditionException("密码错误");
        }
        return TokenUtil.generateToken(dbUser.getId());


    }

    public User getUserById(Long userId) {

        User user = userDao.getUserById(userId);
        UserInfo userInfo = userDao.getUserInfoByUserId(userId);
        user.setUserInfo(userInfo);
        return user;
    }

    public Integer updateUser(User user) throws Exception {

        Long id = user.getId();
        User dbUser = userDao.getUserById(id);
        if (dbUser == null) {
            throw new ConditionException("用户不存在");
        }
        String password = user.getPassword();
        if (!StringUtils.isEmpty(password)) {
            String rawPassword = RSAUtil.decrypt(password);
            String newPassword = MD5Util.sign(rawPassword, user.getSalt(), "utf-8");
            user.setPassword(newPassword);
        }
        return userDao.updateUser(user);
    }

    public Integer updateUserInfo(UserInfo userInfo) {

        Long id = userInfo.getUserId();
        User dbUser = userDao.getUserById(id);
        if (dbUser == null) {
            throw new ConditionException("用户不存在");
        }
        userInfo.setUpdateTime(new Date());

        return userDao.updateUserInfo(userInfo);
    }

    public List<UserInfo> getUserInfoByIds(Set<Long> userIds) {

        return userDao.getUserInfoByUserIds(userIds);
    }

    public PageResult<UserInfo> pageListUserInfos(JSONObject jsonObject) {

        Integer no = jsonObject.getInteger("no");
        Integer size = jsonObject.getInteger("size");
        Integer limit = (no - 1) * size;
        jsonObject.put("limit", limit);
        Integer total = userDao.getPageTotalUserInfos(jsonObject);
        List<UserInfo> userInfoList = new ArrayList<>();
        if (total > 0) {
            userInfoList = userDao.getPageListUserInfos(jsonObject);
        }
        return new PageResult<UserInfo>(total, userInfoList);
    }
}
